<?php

namespace Lettral\UserBundle\Controller;

use Lettral\Helpers\ResponseCreator;

use Symfony\Component\DependencyInjection\ContainerAware;
use Symfony\Component\Security\Core\SecurityContext;
use Symfony\Component\Security\Core\Exception\AuthenticationException;

use FOS\UserBundle\Controller\SecurityController as BaseController;

class SecurityController extends BaseController
{
    public function loginAction()
    {
        $request = $this->container->get('request');
        $session = $request->getSession();

        // get the error if any (works with forward and redirect -- see below)
        if ($request->attributes->has(SecurityContext::AUTHENTICATION_ERROR)) {
            $error = $request->attributes->get(SecurityContext::AUTHENTICATION_ERROR);
        } elseif (null !== $session && $session->has(SecurityContext::AUTHENTICATION_ERROR)) {
            $error = $session->get(SecurityContext::AUTHENTICATION_ERROR);
            $session->remove(SecurityContext::AUTHENTICATION_ERROR);
        } else {
            $error = '';
        }

        if ($error) {
            // TODO: this is a potential security risk (see http://trac.symfony-project.org/ticket/9523)
            $error = "Login ou mot de passe invalide";
            ResponseCreator::getError($error);
        }
        // last username entered by the user
        $lastUsername = (null === $session) ? '' : $session->get(SecurityContext::LAST_USERNAME);

        if ($request->isXmlHttpRequest()) {
        	return $this->container->get('templating')->renderResponse('LettralUserBundle:Security:loginAjax.html.twig', array(
        		'last_username' => $lastUsername, 'error' => $error));       	
        }
        else {
        	return $this->container->get('templating')->renderResponse('LettralUserBundle:Security:login.html.twig', array(
        		'last_username' => $lastUsername, 'error' => $error));
        }
       
    }
}
